package com.mall.service.impl;

import com.mall.common.BusinessException;
import com.mall.common.PageResult;
import com.mall.dto.ProductQueryDTO;
import com.mall.entity.Product;
import com.mall.mapper.ProductMapper;
import com.mall.service.ProductService;
import com.mall.vo.ProductVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    
    @Override
    public PageResult<ProductVO.ProductListVO> getProductPage(ProductQueryDTO queryDTO) {
        int offset = (queryDTO.getPageNum() - 1) * queryDTO.getPageSize();
    
        List<Product> products = productMapper.selectPage(
            offset, 
            queryDTO.getPageSize(),
            queryDTO.getKeyword(),
            queryDTO.getCategoryId(),
            queryDTO.getBrand(),
            queryDTO.getStatus()
        );
        Long total = productMapper.selectCount(
            queryDTO.getKeyword(),
            queryDTO.getCategoryId(),
            queryDTO.getBrand(),
            queryDTO.getStatus()
        );
    
        List<ProductVO.ProductListVO> productVOs = products.stream()
            .map(this::convertToListVO)
            .collect(Collectors.toList());
    
        // 使用PageResult.of静态方法创建结果
        return PageResult.of(total, queryDTO.getPageNum(), queryDTO.getPageSize(), productVOs);
    }
    

    @Override
    public ProductVO.ProductDetailVO getProductDetail(Long productId) {
        Product product = productMapper.selectByIdWithCategory(productId);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        return convertToDetailVO(product);
    }

    @Override
    public PageResult<ProductVO.ProductListVO> searchProducts(String keyword, Integer pageNum, Integer pageSize) {
        int offset = (pageNum - 1) * pageSize;
    
        List<Product> products = productMapper.searchProducts(keyword, offset, pageSize);
        Long total = productMapper.searchProductsCount(keyword);
    
        List<ProductVO.ProductListVO> productVOs = products.stream()
            .map(this::convertToListVO)
            .collect(Collectors.toList());
    
        return PageResult.of(total, pageNum, pageSize, productVOs);
    }
    

    @Override
    public PageResult<ProductVO.ProductListVO> getProductsByCategory(Long categoryId, Integer pageNum, Integer pageSize) {
        // 计算偏移量
        int offset = (pageNum - 1) * pageSize;
        // 原方法体缺少返回语句，补充抛异常
        throw new UnsupportedOperationException("getProductsByCategory 未实现");
    }

    // 管理端：分页获取商品列表（简化版，返回VO列表）
    @Override
    public List<ProductVO> listProducts(Integer pageNum, Integer pageSize, String keyword) {
        int offset = (pageNum - 1) * pageSize;
        List<Product> products = productMapper.selectPage(offset, pageSize, keyword, null, null, null);
        List<ProductVO> voList = new ArrayList<>();
        for (Product p : products) {
            ProductVO vo = new ProductVO();
            BeanUtils.copyProperties(p, vo);
            voList.add(vo);
        }
        return voList;
    }

    // 管理端：新增商品
    @Override
    @Transactional
    public void addProduct(Product product) {
        productMapper.insert(product);
    }

    // 管理端：根据ID获取商品VO
    @Override
    public ProductVO getProductVOById(Long id) {
        Product product = productMapper.selectById(id);
        if (product == null) throw new BusinessException("商品不存在");
        ProductVO vo = new ProductVO();
        BeanUtils.copyProperties(product, vo);
        return vo;
    }
    

    @Override
    public List<ProductVO.ProductListVO> getRecommendProducts(Integer limit) {
        List<Product> products = productMapper.selectRecommendProducts(limit);
        return products.stream()
            .map(this::convertToListVO)
            .collect(Collectors.toList());
    }

    @Override
    public List<ProductVO.ProductListVO> getHotProducts(Integer limit) {
        List<Product> products = productMapper.selectHotProducts(limit);
        return products.stream()
            .map(this::convertToListVO)
            .collect(Collectors.toList());
    }

    @Override
    public List<ProductVO.ProductListVO> getRelatedProducts(Long categoryId, Long excludeId, Integer limit) {
        List<Product> products = productMapper.selectRelatedProducts(categoryId, excludeId, limit);
        return products.stream()
            .map(this::convertToListVO)
            .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void createProduct(Product product) {
        if (productMapper.existsByName(product.getName())) {
            throw new BusinessException("商品名称已存在");
        }
        
        if (product.getStatus() == null) {
            product.setStatus(Product.Status.OFF_SHELF.getCode());
        }
        
        // 去掉以下代码
        // if (product.getSort() == null) {
        //     product.setSort(0);
        // }
        
        productMapper.insert(product);
    }
    
    

    @Override
    @Transactional
    public void updateProduct(Product product) {
        Product existingProduct = productMapper.selectById(product.getId());
        if (existingProduct == null) {
            throw new BusinessException("商品不存在");
        }
        
        // 检查商品名称是否存在(排除自身)
        if (!existingProduct.getName().equals(product.getName()) && 
            productMapper.existsByName(product.getName())) {
            throw new BusinessException("商品名称已存在");
        }
        
        productMapper.updateById(product);
    }

    @Override
    @Transactional
    public void deleteProduct(Long productId) {
        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        productMapper.deleteById(productId);
    }

    @Override
    @Transactional
    public void deleteProducts(Long[] productIds) {
        if (productIds != null && productIds.length > 0) {
            List<Long> idList = new ArrayList<>();
            for (Long productId : productIds) {
                idList.add(productId);
            }
            productMapper.deleteBatchByIds(idList);
        }
    }

    @Override
    @Transactional
    public void updateProductStatus(Long productId, Integer status) {
        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        productMapper.updateStatus(productId, status);
    }

    @Override
    @Transactional
    public void updateProductStock(Long productId, Integer stock) {
        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        productMapper.updateStock(productId, stock);
    }

    @Override
    @Transactional
    public boolean reduceStock(Long productId, Integer quantity) {
        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        if (product.getStock() < quantity) {
            return false;
        }
        return productMapper.reduceStock(productId, quantity) > 0;
    }

    @Override
    @Transactional
    public boolean batchReduceStock(List<Product> products) {
        for (Product product : products) {
            if (!reduceStock(product.getId(), product.getStock())) {
                return false;
            }
        }
        return true;
    }

    @Override
    public boolean existsByName(String name) {
        return productMapper.existsByName(name);
    }

    @Override
    public Product getProductById(Long productId) {
        return productMapper.selectById(productId);
    }

    @Override
    public List<Product> getProductsByIds(List<Long> productIds) {
        List<Product> products = new ArrayList<>();
        for (Long productId : productIds) {
            Product product = productMapper.selectById(productId);
            if (product != null) {
                products.add(product);
            }
        }
        return products;
    }

    /**
     * 转换为列表VO
     */
    private ProductVO.ProductListVO convertToListVO(Product product) {
        ProductVO.ProductListVO vo = new ProductVO.ProductListVO();
        BeanUtils.copyProperties(product, vo);
        return vo;
    }

    /**
     * 转换为详情VO
     */
    private ProductVO.ProductDetailVO convertToDetailVO(Product product) {
        ProductVO.ProductDetailVO vo = new ProductVO.ProductDetailVO();
        BeanUtils.copyProperties(product, vo);
        return vo;
    }
}